//
// Created by Dell on 2020-12-25.
//

#include "jni.h"
#include "cpt.h"

jobject policy_c_to_java(JNIEnv *env, jni_policy *jni_policy) {
    if (jni_policy == nullptr) {
        printf("input data is null!\n");
        return nullptr;
    }
    printf("start data_bean_c_to_java\n");

     // 1. sub policy array
    jsize len = env->GetArrayLength(reinterpret_cast<jarray>(jni_policy->subPolicy));
    printf("point array len: %d\n", len);
    jobjectArray sub_policy_array = env->NewObjectArray(len, m_jni_sub_policy_block.clazz, NULL);
    for (int i = 0; i < len; i++) {
        jobject sub_policy = env->NewObject(m_jni_sub_policy_block.clazz, m_jni_sub_policy_block.constructor);
        env->SetIntField(sub_policy, m_jni_sub_policy_block.position, jni_policy->subPolicy[i].position);
        env->SetIntField(sub_policy, m_jni_sub_policy_block.length, jni_policy->subPolicy[i].length);
        env->SetObjectArrayElement(sub_policy_array, i, sub_policy);
    }

    // 2. policy class
    jobject java_policy = env->NewObject(m_jni_policy_block.clazz, m_jni_policy_block.constructor);
    env->SetIntField(java_policy, m_jni_policy_block.sub_policy_num, jni_policy->sub_policy_num);
    env->SetObjectField(java_policy, m_jni_policy_block.sub_policy, sub_policy_array);

    return java_policy;
}

//void data_bean_java_to_c(JNIEnv *env, jobject data_bean_in, jni_data_bean *data_bean_out) {
void policy_java_to_c(JNIEnv *env, jobject policy_in, jni_policy *jni_policy_out) {
    if (policy_in == nullptr) {
        printf("input data is null!\n");
        return;
    }
    // printf("start data_bean_java_to_c\n");

    // 1. policy
    //jobject rect = env->GetObjectField(data_bean_in, m_data_bean_block.rect);
    jni_policy_out->sub_policy_num = env->GetIntField(policy_in, m_jni_policy_block.sub_policy_num);

    // 2. sub policy array
    jobjectArray sub_policy_array = (jobjectArray) env->GetObjectField(policy_in, m_jni_policy_block.sub_policy);
    jsize len = env->GetArrayLength(sub_policy_array);
    // len = NELEM(data_bean_out->points);
    // printf("policy array len: %ld\n", len); // 注意这个 len 必须等于 NELEM(data_bean_out->points)
    for (int i = 0; i < len; i++) {
        jobject sub_policy = env->GetObjectArrayElement(sub_policy_array, i);
        jni_policy_out->subPolicy[i].position = env->GetIntField(sub_policy, m_jni_sub_policy_block.position);
        jni_policy_out->subPolicy[i].length = env->GetIntField(sub_policy, m_jni_sub_policy_block.length);
    }

    // printf("end data_bean_java_to_c\n");
}